/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from "axios";
import { store } from "../store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
axios.defaults.timeout = 3000000000000;
const errorMessage = {};

//返回其他状态吗
axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
//axios.defaults.withCredentials = true;
//HTTPrequest拦截
axios.interceptors.request.use(
  (config) => {
    store.dispatch("app/setAxiosLoadingNum",1);
    // 缓存最近30次的数据请求参数，做为excel导出数据用
    // console.log(config,'config')
    if (
      config.method == "get" ||
      config.url.indexOf("custmerform/data/") != -1
    ) {
      store.dispatch("app/addRequest", {
        url: config.url,
        params: config.params,
        data: config.data,
      });
    }

    if (
      config.url.indexOf("http://") == -1 &&
      config.url.indexOf("https://") == -1
    ) {
      config.url = `${window.$apiUrl}${config.url}`;
    }

    NProgress.start(); // start progress bar
    const meta = config.meta || {};
    const isToken = meta.isToken === false;
    
    if (store.getters.token && !isToken) {
      config.headers.token = store.getters.token; // 让每个请求携带token--['token']为自定义key 请根据实际情况自行修改
    } else if (!isToken) {
      Message({
        message: " noLogin",
        type: "error",
      });
      store
        .dispatch("organization/user/fedLogOut")
        .then(() => window.$router.push({ path: "/login" }));
      return Promise.reject(new Error("noLogin"));
    }

    // 防止在ie11中出现请求数据缓存的情况
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
      if (config.method == "post") {
        config.data = {
          ...config.data,
          _t: Date.parse(new Date()) / 1000,
        };
      } else if (config.method == "get") {
        config.params = {
          _t: Date.parse(new Date()) / 1000,
          ...config.params,
        };
      }
    }


    // 告诉后端当前语言设置
    const mainLanguage = store.getters.appConfig.language.mainType
    const nowLanguage= store.getters.appConfig.language.type
    if(mainLanguage != nowLanguage){
      config.headers.langType = nowLanguage;
      config.headers.langMType = mainLanguage;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    store.dispatch("app/setAxiosLoadingNum",-1);
    NProgress.done();
    const status = Number(res.status) || 200;
    let message = res.data.info || "error unknown";
    message = message.replace("#field repeat#", "");
    //如果是401则跳转到Login页面
    if (status === 401)
      store
        .dispatch("organization/user/fedLogOut")
        .then(() => window.$router.push({ path: "/login" }));
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
      Message({
        message: message,
        type: "error",
      });
      return Promise.reject(new Error(message));
    } else if (res.data.code && res.data.code != 200) {
      if (res.data.code === 401) {
        Message({
          message: message,
          type: "warning",
        });
        store
          .dispatch("organization/user/fedLogOut")
          .then(() => window.$router.push({ path: "/login" }));
      } else {
        Message({
          message: message,
          type: "error",
        });
      }

      return Promise.reject(new Error(message));
    }
    return res;
  },
  (error) => {
    store.dispatch("app/setAxiosLoadingNum",-1);
    NProgress.done();
    //console.log(error)
    //window.$router.push({ path: '/500' })
    //console.log(JSON.stringify(error),'测试错误信息')
    //console.log(JSON.stringify(error.request),'测试错误信息')
    //console.log(error.config.url,'测试错误信息')
    errorMessage.list = errorMessage.list || [];
    errorMessage.list.push(error.message);
    if (errorMessage.time == null) {
      errorMessage.time = setTimeout(() => {
        if (errorMessage.list.length > 0) {
          Message({
            message: String(errorMessage.list),
            type: "error",
          });
        }

        errorMessage.list = [];
        errorMessage.time = null;
      }, 300);
    }

    return Promise.reject(new Error(error));
  }
);

window.$crud = (url) => {
  return {
    getPage: (params) => {
      return axios({
        url: `${url}/page`,
        method: "get",
        params,
      });
    },
    getList: (params) => {
      return axios({
        url: `${url}s`,
        method: "get",
        params,
      });
    },
    get: (id) => {
      return axios({
        url: `${url}/${id}`,
        method: "get",
      });
    },
    add: (data) => {
      return axios({
        url: `${url}`,
        method: "post",
        data,
      });
    },
    update: (id, data) => {
      return axios({
        url: `${url}/${id}`,
        method: "put",
        data,
      });
    },
    remove: (id) => {
      return axios({
        url: `${url}/${id}`,
        method: "delete",
      });
    },
  };
};

export default axios;
